<template>
  <div class="search-list">
    <!-- 搜索框 -->
    <div class="search-bar">
      <input
      id="inputdom"
        v-model="searchQuery"
        type="text"
        class="search-input"
        placeholder="输入关键词进行搜索..."
        @input="debouncedSearch"
      
      />
    </div>

    <!-- 列表展示 -->
    <ul class="list">
      <li
        v-for="item in list"
        :key="item.uuid"
        class="list-item"
      >
        <div class="list-content"  @click="render_text(item.uuid)">
          <h3 class="list-title" >
            <span >
              <span v-html="heightKeywords(item.标题,searchQuery)"></span>
            </span>
          </h3>
          <p class="list-kind">类型: {{ item.类型 }}</p>
          <p class="list-date">日期: {{ item.日期 }}</p>
          <div class="list-stats">
            <div class="stat-item" >
              <span><Icon type="md-book" />{{ item.阅读量 }}</span>
            </div>
            <div class="stat-item">
                <span><Icon type="md-thumbs-up" style="color: #5cadff;" /> {{ item.点赞数 }}</span>
            </div>
            <div class="stat-item">
                   <span><Icon type="ios-bookmark" style="color: #ff9900;" />{{ item.收藏数 }}</span>
            </div>
          </div>

          
        </div>
       
      </li> 
      <div class="brower_more" ref="loaderElement" ></div>
    </ul>

    <!-- 搜索不到结果时的提示 -->
    <div v-if="list!=undefined&&list.length === 0&&!isloading" class="no-results">
           未找到匹配的结果，请尝试其他关键词。
    </div>
  </div>
</template>

<script setup>
import { ref,nextTick, inject, onUnmounted, onMounted,watch ,defineProps} from "vue";
import { useRouter } from "vue-router";
import  WebSocketRequestPool  from "@/static/js/socket/searchpool.js"
import { getUniqueItemsFromSecondArray_byId } from "@/static/js/array/concat_two_norepeat.js"
import { get_text_by_keywords } from "@/api/community/main.js"
import { customDivision } from "@/static/js/number/division.js"
const websocket_pool=new WebSocketRequestPool("ws://127.0.0.1:8001/response_socket/response/pool/search/article")
websocket_pool.connect()
const firstenter=ref(true)
const loaderElement=ref(null)
let isloading=ref(true)
const user=inject('user')()
const searchQuery = ref("");
const lastsearchQuery=ref("")
const Router = useRouter()
let show_global_button = inject('global_button')
const community = inject('community')()

watch(() => {searchQuery.value }, (newArg, oldArg) => {
  lastsearchQuery.value = oldArg
  
})
const handel_no_space = (str) => {
  return str.replace(/\s+/g, '')
}

// 原始列表数据
const list = ref([]);
const render_text = (id) => {
    if (show_global_button.value) {
        Router.push({ name: 'community_render_text',query:{id:id}});
    } else {
        const route = Router.resolve({
          name: `community_render_text`,
          query: {
            id:id
        } });
        window.open(route.href, '_blank');
    }
}
// 处理 DOM 高亮元素
const heightKeywords = (titles, keywords) => {
  // 将数组转为字符串并拆分为字符数组
  const chars = titles.join('').split('');
  
  // 遍历字符数组，高亮关键字
  const highlighted = chars.map(char => {
    // 如果字符是关键字则包裹红色标签，否则保持原样
    return keywords.includes(char) ? `<span style="color: red;">${char}</span>` : char;
  });

  // 将处理后的字符数组拼接为 HTML 字符串
  return highlighted.join('');
};


// 处理防抖
function debounce(func, delay) {
  let timerId;
  return function(...args) {
    clearTimeout(timerId);
    timerId = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}

// 处理用socket的搜索
const performSearch = () => {
  if (searchQuery.value.length>0) {
     websocket_pool.sendMessage('article',
    { keywords: searchQuery.value, limit:1 ,userid:user.value?.get_user()?.id})
  }
};


const debouncedSearch = debounce(performSearch, 1500)
// 处理sokcet的查询结果
const handeleMessage = (event) => {
  setTimeout(() => {
    let middledata;
    if (lastsearchQuery.value === searchQuery.value) {
      middledata = getUniqueItemsFromSecondArray_byId(list.value, event.detail.data, 'uuid')
      list.value = middledata
    } else { 
      list.value = event.detail.data
      middledata = event.detail.data
    }
    isloading.value = false
    community.value.set_search_text_data(middledata)
   },500)
};


// 处理加载更多直接采用api处理不使用socket
const init_brower = () => {
  const target = loaderElement.value; // 使用 ref 直接获取元素
  if (!target) return;
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
      if (entry.isIntersecting && !isloading.value) {
        isloading.value = true
        handle_textbox_scroll()
      }
    });
  }, {
    root: null, // 使用视口作为根
    rootMargin: '0px',
    threshold: 0.1
  });
  observer.observe(target)
}

//实际处理滚动动态加载数据
const handle_textbox_scroll = async () => {
  isloading.value = false
  if (firstenter.value) { 
    // 第一次进入直接根据搜索词处理第一行
    const data =await get_text_by_keywords(searchQuery.value, user.value?.get_user()?.id,
    1
    )
    list.value = data
    community.value.set_search_text_data(data)
    firstenter.value = false
    return 
  }
  
   
    const data =await get_text_by_keywords(searchQuery.value, user.value?.get_user()?.id,
    customDivision(community.value.get_search_text_data().length, 10)
    )
    const middledata = getUniqueItemsFromSecondArray_byId(list.value, data, 'uuid')
    list.value.push(...middledata)
    community.value.set_search_text_data(list.value)
  
};

onMounted(async () => {
  await nextTick()
  init_brower()
  searchQuery.value = community.value.get_searchQuery()
  lastsearchQuery.value = community.value.get_searchQuery()
  if (community.value.get_search_text_data().length > 0) {
    list.value = community.value.get_search_text_data()
    isloading.value=false
  } else { 
    // 使用api处理,避免socket导致的多种防抖问题
    const data =await get_text_by_keywords(searchQuery.value, user.value?.get_user()?.id)
    list.value = data
    isloading.value = false
    community.value.set_search_text_data(data)
  }
 
  // 必须处理的
   setTimeout(() => {
   isloading.value=false
  }, 5000);
  window.addEventListener('article_search', handeleMessage)
})

onUnmounted(() => { 
  // 避免连接资源泄漏
  websocket_pool.disconnect()
  window.removeEventListener('article_search',handeleMessage )
})
</script>

<style scoped>
/* 主色调 */
:root {
  --primary-color: #50e3c2;
  --primary-color-hover: #3cb89d;
  --text-color: #333;
  --secondary-text-color: #666;
  --hover-text-color: #444; /* 悬浮时字体颜色 */
  --bg-color: #f9f9f9;
  --card-bg-color: #ffffff;
  --shadow-color: rgba(0, 0, 0, 0.1);
}

/* 页面整体样式 */
.search-list {
  max-width: 700px;
  margin: 50px auto;
  font-family: "Arial", sans-serif;
  color: var(--text-color);
  background: var(--card-bg-color);
  border-radius: 12px;
  box-shadow: 0 6px 15px var(--shadow-color);
  padding: 20px;
  overflow: hidden;
}

/* 搜索框样式 */
.search-bar {
  text-align: center;
  margin-bottom: 20px;
}

.search-input {
  width: 100%;
  padding: 14px 18px;
  font-size: 16px;
  border: 1px solid black;
  border-radius: 10px;
  transition: all 0.3s ease-in-out;
  box-shadow: 0 2px 4px var(--shadow-color);
}

.search-input:focus {
  outline: none;
  border-color: var(--primary-color-hover);
  box-shadow: 0 4px 8px rgba(80, 227, 194, 0.4);
}

/* 列表样式 */
.list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.list-item {
  background: var(--bg-color);
  padding: 20px;
  margin-bottom: 15px;
  border-radius: 10px;
  border: 1px solid #ddd;
  transition: background-color 0.3s, transform 0.2s, box-shadow 0.2s, color 0.3s;
  cursor: pointer;
  box-shadow: 0 2px 5px var(--shadow-color);
}

.list-item:hover {
  background: var(--primary-color);
  color: var(--hover-text-color); /* 悬浮字体颜色 */
  transform: translateY(-3px);
  box-shadow: 0 6px 15px rgba(80, 227, 194, 0.4);
}

.list-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.list-title {
  font-size: 18px;
  font-weight: bold;
  margin: 0;
}

.list-kind,
.list-date {
  font-size: 14px;
  color: var(--secondary-text-color);
}

.list-stats {
  display: flex;
  gap: 20px;
  margin-top: 10px;
}

.stat-item {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-color);
}

.stat-item span {
  font-weight: bold;
  color: var(--primary-color);
}

/* 无结果提示样式 */
.no-results {
  text-align: center;
  color: var(--secondary-text-color);
  font-size: 16px;
  margin-top: 20px;
}

.brower_more{
    width: 100%;
    height: 20px;
}
/* 这是浏览标记 */
.browse_loader_sifttext{
  width: 100%;
  height: 25px;
  text-align: center;
  font-size: 18px;
  /* color: #1a73e8; */
  margin-top: 0; /* 确保不会影响布局 */
  visibility: visible; /* 确保元素可见 */
  margin-bottom: 20px;
}
</style>